package com.hqyj.paimaisys.web;

import com.hqyj.paimaisys.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${accessTokenExpireTime}")
    private Integer accessTokenExpireTime;

    /**
     * 校验token的正确性
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //1. 从请求头中得到token的值
        String token  = request.getHeader("token");

        // 在redis中校验 token是否有效。   不是 hid
        System.out.println("========token ======");
        System.out.println(token);
        System.out.println("-------------------------");
        //2. 利用tokenUtil校验token的正确性
        //boolean flag = TokenUtil.verify(token);
        //要使用 redis进行校验

        String hid = redisTemplate.opsForValue().get(token);

        //3.1 校验成功，放行, 把有效期增长
        if(hid != null) {
            System.out.println("--------放行----------");
            redisTemplate.expire(token,accessTokenExpireTime , TimeUnit.SECONDS);
            return true;

        }
        //3.2 校验失败， 拦到登录
        else{
            System.out.println("-------拦截，要求先登录----------");
           //给前端页面发送鉴权失败的响应， 采用json格式 {“code”, 401}
            response.getWriter().write("{\"code\":401}");
            return false;
        }
    }

}
